package com.sherlocky.util;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONSerializer;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.rework.joss.persistence.convention.ConventionUtils;

public abstract class GridUtils {
	// 页面的最大行数
	public static final String PAG_MAX_PAGE_ITEMS = "rows";
	public static final int DEFAULT_PAG_MAX_PAGE_ITEMS = 10;
	
	// 当前页码
	public static final String JSON_KEY_CUR_PAG = "page";
	// 分页总数
	public static final String JSON_KEY_TOTAL_PAGES = "total";
	// 记录总数
	public static final String JSON_KEY_TOTAL_RECORDS = "records";
	// 记录
	public static final String JSON_KEY_RECORD = "rows";
	//自定义数据
	public static final String JSON_KEY_USERDATA = "userdata";
	
	/**
	 * 当前页码
	 * @param request
	 * @return
	 */
	public static int getPageNum(HttpServletRequest request) {
		String page = request.getParameter(JSON_KEY_CUR_PAG);
		return NumberUtils.isNumber(page) ? Integer.parseInt(page) : 1;
	}
	
	/**
	 * 每页显示记录数
	 * @param request
	 * @return
	 */
	public static int getInternal(HttpServletRequest request) {
		String page = request.getParameter(PAG_MAX_PAGE_ITEMS);
		return NumberUtils.isNumber(page) ? Integer.parseInt(page) : 10;
	}
	
	/**
	 * 列表排序
	 * @param request
	 * @return
	 */
	public static String getOrderby(HttpServletRequest request) {
		String orderby2 = request.getParameter("orderby");
		if(StringUtils.isNotEmpty(orderby2)) {
			//如果存在自定义的排序方式，则使用这种，反之使用列表默认的排序方式
			return orderby2;
		}
		String orderby = request.getParameter("sidx"); //排序字段
		String sord = request.getParameter("sord"); //升降
		return StringUtils.isNotBlank(orderby) ? orderby + " " + StringUtils.defaultIfEmpty(sord,"") : "";
	}
	
	public static int getTotalPages(int records, int limit) {
		if(records <= 0) {
			return 0;
		}
		int totalPages = 0;
		totalPages = records / Math.max(limit, 1);
		totalPages = records % Math.max(limit, 1) == 0 ? totalPages : totalPages + 1;
		return totalPages;
	}
	
	/**
	 * 为jqGrid构造json格式的数据
	 * @param limit 每页显示记录数
	 * @param page 页码
	 * @param records 总记录数
	 * @param rows 数据
	 * @return
	 */
	public static String constructJsonData4Grid(int limit, int page, int records, List rows,Map userData) {
		int totalPages = getTotalPages(records, limit);
		if (page > totalPages) {
			page = totalPages;
		}
		String json = JSONSerializer.toJSON(
				ConventionUtils.toMap(JSON_KEY_TOTAL_PAGES, totalPages, 
						JSON_KEY_CUR_PAG, page, 
						JSON_KEY_TOTAL_RECORDS, records, 
						JSON_KEY_RECORD, rows,
						JSON_KEY_USERDATA, userData)).toString();
		return json;
	}

}
